package com.key.win.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.key.win.base.exception.BizException;
import com.key.win.base.page.MybatisPageServiceTemplate;
import com.key.win.base.util.BeanUtils;
import com.key.win.base.util.SingleSoldierConstantUtils;
import com.key.win.base.web.PageRequest;
import com.key.win.base.web.PageResult;
import com.key.win.system.dao.SysDeviceDao;
import com.key.win.system.dao.SysOrganDeviceDao;
import com.key.win.system.dao.SysUserDeviceDao;
import com.key.win.system.model.SysDevice;
import com.key.win.system.model.SysOrgan;
import com.key.win.system.model.SysUser;
import com.key.win.system.model.SysUserDevice;
import com.key.win.system.service.SysDeviceService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SysDeviceServiceImpl extends ServiceImpl<SysDeviceDao, SysDevice> implements SysDeviceService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SysUserDeviceDao sysUserDeviceDao;
    @Autowired
    private SysOrganDeviceDao sysOrganDeviceDao;

    @Override
    public List<SysDevice> findSysDevice(SysDevice sysDevice) {
        LambdaQueryWrapper<SysDevice> lambdaQueryWrapper = new LambdaQueryWrapper<SysDevice>();
        if (sysDevice != null) {
            if (StringUtils.isNotBlank(sysDevice.getName())) {
                lambdaQueryWrapper.eq(SysDevice::getName, sysDevice.getName());
            }
            if (StringUtils.isNotBlank(sysDevice.getCode())) {
                lambdaQueryWrapper.eq(SysDevice::getCode, sysDevice.getCode());
            }
        }
        List<SysDevice> list = this.list(lambdaQueryWrapper);
        return list;
    }

    @Override
    public PageResult<SysDevice> findSysDeviceByPaged(PageRequest<SysDevice> t) {

        MybatisPageServiceTemplate<SysDevice, SysDevice> mybatiesPageServiceTemplate = new MybatisPageServiceTemplate<SysDevice, SysDevice>(this.baseMapper) {
            @Override
            protected AbstractWrapper constructWrapper(SysDevice sysDevice) {
                LambdaQueryWrapper<SysDevice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                if (StringUtils.isNotBlank(sysDevice.getName())) {
                    lambdaQueryWrapper
                            .like(SysDevice::getName, sysDevice.getName())
                            .or()
                            .like(SysDevice::getCode, sysDevice.getName());
                }

                return lambdaQueryWrapper;
            }
        };

        return mybatiesPageServiceTemplate.doPagingQuery(t);
    }


    @Override
    public boolean saveOrUpdateDevice(SysDevice sysDevice) {
        SysDevice po = null;
        if (StringUtils.isNotBlank(sysDevice.getId())) {
            po = this.getById(sysDevice.getId());
            if (po == null) {
                logger.error("设备不存在!");
                throw new BizException("设备不存在!");
            }
            if (!po.getCode().equals(sysDevice.getCode())) {
                logger.error("设备code[{}]已锁定，不允许修改！", sysDevice.getCode());
                throw new BizException("设备code已锁定，不允许修改！!");
            }
            BeanUtils.copyProperties(sysDevice, po);
        } else {
            po = sysDevice;
            List<SysDevice> sysDevices = this.findSysDeviceByCode(sysDevice.getCode());
            if (!CollectionUtils.isEmpty(sysDevices)) {
                logger.error("设备code[{}]已存在！", sysDevice.getCode());
                throw new BizException("设备code已存在！");
            }
        }
        boolean b = this.saveOrUpdate(sysDevice);
//        if (StringUtils.isNotBlank(sysDevice.getUserId())) {
//            Set<String> userIds = Arrays.asList(sysDevice.getUserId().split(",")).stream().collect(Collectors.toSet());
//            if (!CollectionUtils.isEmpty(userIds)) {
//                sysUserDeviceDao.deleteUserDevice(null, sysDevice.getId());
//                sysUserDeviceDao.saveBatchUserIdsAndDeviceId(userIds, sysDevice.getId());
//                /*userIds.forEach(userId -> {
//                    SysUserDevice sysUserDevice = new SysUserDevice();
//                    sysUserDevice.setDeviceId(sysDevice.getId());
//                    sysUserDevice.setUserId(userId);
//                    sysUserDeviceDao.insert(sysUserDevice);
//                });*/
//            }
//        }
        if (StringUtils.isNotBlank(sysDevice.getOrganId())) {
            Set<String> organIds = Arrays.asList(sysDevice.getOrganId().split(",")).stream().collect(Collectors.toSet());
            if (!CollectionUtils.isEmpty(organIds)) {
                sysOrganDeviceDao.deleteOrganDevice(null, sysDevice.getId());
                sysOrganDeviceDao.saveBatchOrganIdsAndDeviceId(organIds, sysDevice.getId());
                /*organIds.forEach(organId -> {
                    SysOrganDevice sysOrganDevice = new SysOrganDevice();
                    sysOrganDevice.setDeviceId(sysDevice.getId());
                    sysOrganDevice.setOrganId(organId);
                    sysOrganDeviceDao.insert(sysOrganDevice);
                });*/
            }
        }
        List<SysUserDevice> sysUserDevices = sysDevice.getSysUserDevices();
        if (!CollectionUtils.isEmpty(sysUserDevices)) {
            Set<String> organIds = sysUserDevices.stream().map(SysUserDevice::getOrganId).collect(Collectors.toSet());
            for (String organId : organIds) {
                sysUserDeviceDao.deleteUserDevice(null, organId, sysDevice.getId());
            }
            sysUserDeviceDao.saveBatchUserIdsAndOrganIdsAndDeviceId(sysUserDevices, sysDevice.getId());
        }
        return b;
    }

    private List<SysDevice> findSysDeviceByCode(String code) {
        SysDevice sysDevice = new SysDevice();
        sysDevice.setCode(code);
        return this.findSysDevice(sysDevice);
    }

    @Override
    public List<SysDevice> findDeviceByOrganId(String organId) {
        if (StringUtils.isBlank(organId)) {
            logger.error("机构id为空!");
            throw new IllegalArgumentException("机构id为空!");
        }
        if (SingleSoldierConstantUtils.ORGAN_TREE_PARENT_ID.equals(organId)) {
            return this.list();
        }

        return sysOrganDeviceDao.findDeviceByOrganId(organId);
    }

    public SysDevice getSysDeviceFullById(String id) {
        SysDevice byId = this.getById(id);
        List<SysOrgan> organByDeviceId = sysOrganDeviceDao.findOrganByDeviceId(id);
        List<SysUser> userByDeviceId = sysUserDeviceDao.findUserByDeviceId(id);
        byId.setSysOrgans(organByDeviceId);
        byId.setSysUsers(userByDeviceId);
        return byId;
    }

    @Override
    public boolean deleteById(String id) {
        SysDevice sysDeviceFullById = this.getSysDeviceFullById(id);
        if (!CollectionUtils.isEmpty(sysDeviceFullById.getSysOrgans())) {
            logger.error("删除SysDevice时，发现关联[{}]个SysOrgan！", sysDeviceFullById.getSysOrgans().size());
            throw new BizException("请先解除关联的机构信息！");
        }
        if (!CollectionUtils.isEmpty(sysDeviceFullById.getSysUsers())) {
            logger.error("删除SysDevice时，发现关联[{}]个SysUser！", sysDeviceFullById.getSysUsers().size());
            throw new BizException("请先解除关联的用户信息！");
        }
        return this.removeById(id);
    }

    @Override
    public List<SysDevice> findDeviceByOrganIds(List<String> organIds) {
        return sysOrganDeviceDao.findDeviceByOrganIds(organIds);
    }
}
